package com.kfm.mvn.servlet;

import com.kfm.mvn.util.Constant;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

@WebServlet("/download/*")
public class DownloadServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String download = req.getParameter("download");
        if (download != null){
            // 以附件形式下载
            resp.setHeader("content-Disposition", "attachment");
        }
        // /上下文路径/servletUrl/xxxx
        String requestURI = req.getRequestURI();

        // 上下文路径
        String contextPath = req.getContextPath();

        // servletUrl
        String servletPath = req.getServletPath();

        String replace = requestURI.replace(contextPath, "");
        String filePath = replace.replace(servletPath, "");

        System.out.println(filePath);

        File file = new File(Constant.UPLOAD_PATH, filePath);

        try (FileInputStream fis = new FileInputStream(file);){
            // 响应字节内容
            fis.transferTo(resp.getOutputStream());
        } catch (IOException ex){
            resp.setContentType("text/plain;charset=utf-8");
            resp.getWriter().println("未找到文件");
        }
    }
}
